import type { Router } from 'express';

// In-memory subscribers per live room (SSE)
export const liveSubscribers = new Map<string, Set<any>>();

export function sendToLiveRoom(roomId: string, event: 'message'|'gift'|'system', payload: any) {
  const set = liveSubscribers.get(roomId);
  if (!set) return;
  const data = `event: ${event}\n` + `data: ${JSON.stringify(payload)}\n\n`;
  for (const res of set) {
    try { res.write(data); } catch {}
  }
}

export function attachLiveSSE(router: Router, basePath: string) {
  // GET {basePath}/:id/stream
  router.get(basePath + '/:id/stream', async (req, res) => {
    const roomId = String((req.params as any).id);

    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    (res as any).flushHeaders?.();

    if (!liveSubscribers.has(roomId)) liveSubscribers.set(roomId, new Set());
    liveSubscribers.get(roomId)!.add(res);

    const keepAlive = setInterval(() => {
      try { res.write(': ping\n\n'); } catch {}
    }, 30000);

    // initial system event
    try {
      const welcome = { id: String(Date.now()), content: '欢迎来到直播间', timestamp: new Date(), isSystem: true };
      const data = `event: system\n` + `data: ${JSON.stringify(welcome)}\n\n`;
      res.write(data);
    } catch {}

    req.on('close', () => {
      clearInterval(keepAlive);
      liveSubscribers.get(roomId)?.delete(res);
    });
  });
}

